#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author  : Hombin
@File    : data_platform_etl.py
@Time    : 2018/9/18 11:46
@Note    : 对外数据接口 ETL模块
"""


class DataApiPlatformETL(object):
    def __init__(self, log):
        self.log = log

    @staticmethod
    def __fix_time(date_time):
        if "-" not in date_time:
            return date_time

        if ":" in date_time:
            date_time = date_time.split(" ")[0]

        ymd_list = date_time.split("-")
        return ymd_list[0] + u"年" + ymd_list[1] + u"月" + ymd_list[2] + u"日"

    def gsxt_etl(self, json_data):
        if not isinstance(json_data, dict):
            self.log.error("传入数据类型错误：data = {}".format(json_data))
            return None

        # 抽取基本信息
        basic_info = {}
        try:
            basic_info = {
                # 公司名称
                "company": json_data["company"],
                # 省份
                "province": json_data.get("province", ""),
                # 注册时间
                "registered_date": self.__fix_time(json_data.get("registered_date", "")),
                # 注册机关
                "registered_address": json_data.get("registered_address", ""),
                # 转换前的注册资本
                "registered_capital": json_data.get("src_registered_capital", ""),
                # 注册号/统一社会信用号
                "code": json_data.get("code", ""),
                # 法人
                "legal_representative": json_data.get("legal_man", ""),
                # 经营状态
                "business_status": json_data.get("business_status", ""),
                # 核准日期
                "approval_date": self.__fix_time(json_data.get("hezhun_date", "")),
                # 公司类型
                "enterprise_type": json_data.get("enterprise_type", ""),
                # 经营范围
                "business_scope": json_data.get("business_scope", ""),
                # 营业期限
                "period": json_data.get("period", ""),
                # 公司地址
                "address": json_data.get("address", ""),
            }
        except BaseException as e:
            self.log.exception(e)
            self.log.error("工商基本信息字段有缺失：{}".format(json_data))

        # 兼容DB数据的 code字段
        if not basic_info["code"]:
            unified_social_credit_code = json_data.get("unified_social_credit_code", "")
            registered_code = json_data.get("registered_code", "")
            if unified_social_credit_code:
                basic_info["code"] = unified_social_credit_code
            elif registered_code:
                basic_info["code"] = registered_code

        # 兼容DB数据的 period字段
        if u"至" in basic_info["period"]:
            date_from = basic_info["period"].split(u"至")[0]
            date_to = basic_info["period"].split(u"至")[1]
            basic_info["period"] = self.__fix_time(date_from) + u"至" + self.__fix_time(date_to)

        # 抽取主要人员
        key_person = json_data.get("key_person", [])

        # 抽取分支机构
        branch_info = json_data.get("branch", [])
        for branch_item in branch_info:
            branch_com = branch_item.get("compay_name", "")
            if branch_com == "":
                branch_com = branch_item.get("company_name", "")
            branch_item["company_name"] = branch_com
            branch_item.pop("compay_name")

        # 抽取出资信息
        contributor_info = json_data.get("contributor_information", [])

        # 抽取动产抵押
        chattel_mortgage_info = json_data.get("chattel_mortgage_info", [])

        # 抽取股权出质
        equity_pledged_info = json_data.get("equity_pledged_info", [])

        json_resp = {
            # 基本信息
            "basic_info": basic_info,
            # 主要人员
            "key_person": key_person,
            # 分支机构
            "branch_info": branch_info,
            # 出资信息
            "contributor_info": contributor_info,
            # 动产抵押
            "chattel_mortgage_info": chattel_mortgage_info,
            # 股权出质
            "equity_pledged_info": equity_pledged_info,
        }

        return json_resp

    def shixin_etl(self, json_data):
        if not isinstance(json_data, dict):
            self.log.error("传入数据类型错误：data = {}".format(json_data))
            return None

        json_resp = {}
        try:
            json_resp = {
                # 失信被执行人主体
                "shixin_name": json_data.get("i_name", ""),
                # 案件代码
                "case_id": json_data.get("case_id", ""),
                # 执行法院
                "court_name": json_data.get("court", ""),
                # 被执行人的履行情况
                "fulfilment": json_data.get("performance", ""),
                # 省份
                "province": json_data.get("province", ""),
                # 发布日期
                "publish_date": self.__fix_time(json_data.get("publish_date", "")),
                # 生效法律文书确定的义务
                "definite_duty": json_data.get("duty", ""),
                # 失信被执行人行为具体情形
                "shixin_behavior": json_data.get("disrupt_type_name", ""),
            }
        except BaseException as e:
            self.log.exception(e)
            self.log.error("失信被执行人数据有缺失：data = {}".format(json_data))

        return json_resp

    def zhixing_etl(self, json_data):
        if not isinstance(json_data, dict):
            self.log.error("传入数据类型错误：data = {}".format(json_data))
            return None

        json_resp = {}
        try:
            json_resp = {
                # 法院名称
                "court_name": json_data.get("court", ""),
                # 被执行人姓名/名称
                "zhixing_name": json_data.get("i_name", ""),
                # 案号
                "case_id": json_data.get("case_id", ""),
                # 立案时间
                "case_date": self.__fix_time(json_data.get("case_date", "")),
                # 执行金额
                "exec_money": json_data.get("exec_money", ""),
                # 身份证号码/组织机构代码
                "code": json_data.get("party_card_num", ""),
            }

            if str(json_resp["code"]).strip() == "0" or str(json_resp["code"]).strip() == "":
                json_resp["code"] = ""

        except BaseException as e:
            self.log.exception(e)
            self.log.error("被执行人信息数据有缺失：data = {}".format(json_data))

        return json_resp

    def wenshu_etl(self, json_data):
        if not isinstance(json_data, dict):
            self.log.error("传入数据类型错误：data = {}".format(json_data))
            return None

        json_resp = {}
        try:
            json_resp = {
                # 公告时间
                "bulletin_date": self.__fix_time(json_data.get("bulletin_date", "")),
                # 判决日期
                "case_date": self.__fix_time(json_data.get("case_date", "")),
                # 案件代码
                "case_id": json_data.get("case_id", ""),
                # 案件名称
                "case_name": json_data.get("case_name", ""),
                # 法院
                "court_name": json_data.get("court", ""),
                # 详情页地址
                "judgment_url": json_data.get("url", ""),
            }
        except BaseException as e:
            self.log.exception(e)
            self.log.error("裁判文书信息数据有缺失：data = {}".format(json_data))

        return json_resp

    def news_etl(self, json_data):
        if not isinstance(json_data, dict):
            self.log.error("传入数据类型错误：data = {}".format(json_data))
            return None

        json_resp = {}
        try:
            json_resp = {
                # 发布时间
                "publish_date": self.__fix_time(json_data.get("publish_time", "")),
                # 关键字
                "keyword": json_data.get("keyword", ""),
                # 标题
                "news_title": json_data.get("title", ""),
                # 作者
                "news_author": json_data.get("author", ""),
                # 新闻链接
                "news_href": json_data.get("href", ""),
                # 概要
                "summary": json_data.get("summary", ""),
                # 情感类型
                "sentiment": json_data.get("sentiment", ""),
            }
        except BaseException as e:
            self.log.exception(e)
            self.log.error("百度新闻信息数据有缺失：data = {}".format(json_data))

        return json_resp
